package com.ruoyi.manufacturer;

import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.third.domain.ThirdPlatform;
import com.ruoyi.third.service.IThirdPlatformService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 平台接入任务
 * 1、在应用启动后，开启各接入服务
 * 2、定时检测各服务是否异常，并可触发自定义的定时任务
 */
@Component
public class PlatformTask implements ApplicationRunner {
    public static Map<String, IPlatform> platformMap = new ConcurrentHashMap<>();

    @Autowired
    private IThirdPlatformService thirdPlatformService;

    /**
     * 获取接入插件
     * @param pfCode
     * @return
     */
    public static IPlatform getHandler(String pfCode){
        return platformMap.get(pfCode);
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        Collection<IPlatform> handlerList = SpringUtils.getBeanList(IPlatform.class);
        for(IPlatform handler:handlerList){
            platformMap.put(handler.getPfCode(), handler);
            ThirdPlatform thirdPlatform = thirdPlatformService.selectThirdPlatformByCode(handler.getPfCode());
            if(thirdPlatform != null && thirdPlatform.getStatus().equals("1")){
                startPlatform(handler, thirdPlatform);
            }
        }
    }

    /**
     * 启动指定的接入平台插件
     * @param thirdPlatform 平台信息，包括配置
     */
    public void startPlatform(IPlatform handler, ThirdPlatform thirdPlatform){
        try {
            boolean ret = handler.start(thirdPlatform);
            if(ret){
                thirdPlatform.setRunning("1");
            }else{
                thirdPlatform.setRunning("0");
            }
        }catch (Exception e){
            e.printStackTrace();
            thirdPlatform.setRunning("0");
        }
        thirdPlatformService.updateThirdPlatform(thirdPlatform);
    }

    /**
     * 定时检测启动的插件是否停止,10分钟一次
     */
    @Scheduled(fixedDelay = 600000, initialDelay = 300000)
    public void alive(){
        for(IPlatform handler: platformMap.values()){
            ThirdPlatform thirdPlatform = thirdPlatformService.selectThirdPlatformByCode(handler.getPfCode());
            if(thirdPlatform != null && thirdPlatform.getRunning().equalsIgnoreCase("1") && !handler.alive(thirdPlatform)){
                startPlatform(handler, thirdPlatform);
            }
        }
    }
}
